<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>智能路线生成中</title>
    <meta name="viewport"
      content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <!-- <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"> -->
    <link rel="stylesheet" media="screen" href="css/style.css">
    <script src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
    <script src="https://lf3-cdn-tos.bytegoofy.com/obj/goofy/developer/jssdk/jssdk-1.2.1.js"></script>
    <script src="./js/jquery.js"></script>
    <script src="./js/particles.min.js"></script>
  </head>
  <body>
    <div id="particles-js"></div>
    <div class="datitle">
      <p>AI智能行程规划助手</p>
      <span>以大数据为基础，高效规划乡村旅游行程。</span>
    </div>
    <div class="title">

    </div>
    <div class="content"></div>
    <script src="./js/app.js"></script>
  </body>
  <script>
    var systemType = null;

    // var baseUrl = `http://swklocaltown.go.cnitcs.net`; //测试地址
    var baseUrl = `https://www.nbomb.cloud:8089`; //线上地址
    var sendData = {},
      type = null,
      ques = {},
      gptData = {
        title: {
          end: false,
          str: ''
        },
        content: {
          end: false,
          str: ''
        },
      },
      localData = null;

    if (getUrlparam('type')) {
      type = getUrlparam('type')
    }

    if (getUrlparam('sendData')) {
      sendData = JSON.parse(decodeURIComponent(getUrlparam('sendData')))
      // console.log(sendData, 'sendData');
      getQuesStr()
    }

    function getQuesStr() {
      $.ajax({
        type: 'post',
        url: baseUrl + "/route/village/startTravel",
        contentType: 'application/json;charset=utf-8',
        data: JSON.stringify(sendData),
        success: (res) => {
          // console.log(res)
          if (res.code == 200) {
            ques = res.data;
            askQues();
          } else {
            // alert(res.msg);
            // wx.miniProgram.navigateBack()
          }
        },
        error: (err) => {

        }
      })
    }

    function askQues() {
      // if (ques.title) {
      // 	let titSource = new EventSource("https://www.nbomb.cloud/chat/sse?prompt=" + ques.title + "&key=&id=" + ques
      // 		.travelId);
      // 	titSource.onmessage = function(e) {
      // 		if (e.data) {
      // 			let data = JSON.parse(e.data);
      // 			if (data.content) {
      // 				if (data.content == 'error') {
      // 					getLocalData('title')
      // 				} else {
      // 					gptData.title.str += data.content;
      // 					$('.title').text(gptData.title.str)
      // 				}
      // 			}
      // 		}
      // 	};
      // 	titSource.onerror = function(evt) {
      // 		if (!gptData.title.str) {
      // 			getLocalData('title')
      // 		} else {
      // 			gptData.title.end = true;
      // 			chkEnd()
      // 		}

      // 		titSource.close()
      // 	}
      // }

      if (ques.content) {
        let conSource = new EventSource("https://www.nbomb.cloud/chat/sse?prompt=" + ques.content + "&key=&id=" +
          ques.travelId);
        conSource.onmessage = function(e) {

          if (e.data) {
            let data = JSON.parse(e.data);
            if (data.content) {
              if (data.content == 'error') {
                getLocalData('content');
                getLocalData('title');
              } else {
                gptData.content.str += data.content;
                $('.content').text(gptData.content.str)
              }
            }
          };
        };
        conSource.onerror = function(evt) {
          if (!gptData.content.str) {
            getLocalData('content')
          } else {
            gptData.content.end = true;
            // chkEnd()
          }
          conSource.close()

          if (ques.title) {
            let titSource = new EventSource("https://www.nbomb.cloud/chat/sse?prompt=" + ques.title +
              "&key=&id=" + ques
              .travelId);
            titSource.onmessage = function(e) {
              if (e.data) {
                let data = JSON.parse(e.data);
                if (data.content) {
                  if (data.content == 'error') {
                    getLocalData('title');
                  } else {
                    gptData.title.str += data.content;
                    $('.title').text(gptData.title.str)
                  }
                }
              }
            };
            titSource.onerror = function(evt) {
              if (!gptData.title.str) {
                getLocalData('title')
              } else {
                gptData.title.end = true;
                chkEnd()
              }

              titSource.close()
            }
          };


        }
      }
    }

    function getLocalData(type) {
      if (localData === "content") {
        setLocalData(type)
        return false
      };
      $.ajax({
        type: 'post',
        url: baseUrl + "/route/village/getTemplateMsg",
        contentType: 'application/json;charset=utf-8',
        data: JSON.stringify({
          travelId: ques.travelId,
        }),
        success: (res) => {
          if (res.code == 200) {
            localData = res.data;
            setLocalData(type)
          } else {
            alert(res.msg);
          };
        },
        error: (err) => {}
      })
    }

    function setLocalData(type) {
      gptData[type].str = localData[type];
      setStrShow(type)
    }

    function setStrShow(type) {
      console.log(type)
      if (type) {
        let length = 1,
          max = gptData[type].str.length;

        let index = setInterval(() => {
          if (length > max) {
            clearInterval(index);
            gptData[type].end = true;
            chkEnd()
          } else {
            let str = gptData[type].str.substring(0, length);
            $('.' + type).text(str)
            length++;
          }
        }, 50)
      };
    }



    function chkEnd() {
      if (gptData.title.end && gptData.content.end) {
        $.ajax({
          type: 'post',
          url: baseUrl + "/route/village/saveGptMessage",
          contentType: 'application/json;charset=utf-8',
          data: JSON.stringify({
            travelId: ques.travelId,
            title: gptData.title.str,
            content: gptData.content.str
          }),
          success: (res) => {
            if (res.code == 200) {
              setTimeout(() => {
                wx.miniProgram.getEnv((envRes) => {
                  if (envRes.miniprogram) {
                    if (type == 'reCreate') {
                      wx.miniProgram.postMessage({ data: { travelId: ques.travelId, unUser: 0 } });
                      wx.miniProgram.navigateBack(-1);
                    } else {
                      wx.miniProgram.redirectTo({
                        url: '/pagesLuxian/pages/info/index?travelId=' + ques.travelId +
                          '&unUser=0'
                      });
                    }
                  }
                })
                tt.miniProgram.getEnv((envRes) => {
                  if (envRes.miniprogram) {
                    if (type == 'reCreate') {
                      tt.miniProgram.postMessage({ data: { travelId: ques.travelId, unUser: 0 } });
                      tt.miniProgram.navigateBack(-1);
                    } else {
                      tt.miniProgram.redirectTo({
                        url: '/pagesLuxian/pages/info/index?travelId=' + ques.travelId +
                          '&unUser=0'
                      });
                    }
                  }
                })
              }, 3000);
            } else {
              alert(res.msg);
            };
          },
          error: (err) => {}
        });
      }
    }


    function getUrlparam(param) {
      const reg = new RegExp('(^|&)' + param + '=([^&]*)(&|$)');
      const r = window.location.search.substr(1).match(reg) || window.location.hash.substring((window
        .location.hash
        .search(/\?/)) + 1).match(reg);
      if (r != null) {
        return decodeURIComponent(r[2]);
      }
    }
  </script>
</html>
